<template>
  <div id="userlist">
    <div class="top">
      <el-autocomplete
        v-model="state"
        prefix-icon="el-icon-search"
        :fetch-suggestions="querySearchAsync"
        placeholder="请输入用户名"
        @select="handleSelect"
        @keydown.enter.native="addContacts"
      ></el-autocomplete>
      <div class="add" @click="addContacts">
        <i class="el-icon-circle-plus-outline"></i>
      </div>
    </div>
    <div class="list">
      <div
        class="content"
        v-for="res in userlist"
        :key="res.id"
        :id="res.id"
        @click="getSingleUser(res)"
        :class="{ clickBag: res.id == indexId }"
      >
        <div class="img">
          <div class="count" v-show="res.count != 0">
            {{ res.count }}
          </div>
          <!-- 使用 el-avatar 组件来显示头像 -->
          <el-avatar :src="res.avatar" :size="45"></el-avatar>
        </div>
        <div class="center">
          <div class="username">
            <span>{{ res.username }}</span>
          </div>
          <div class="message">
            <span>{{ res.content }}</span>
          </div>
        </div>
        <div class="time">
          <span>{{ res.time }}</span>
        </div>
      </div>
    </div>
    <!-- 模态框 -->
    <div id="dialog" @mousedown="handleMouseDown">
      <el-dialog
        :visible.sync="dialogVisible"
        width="45%"
        :before-close="handleClose"
        ref="dialog"
        :draggable="true"
      >
        <div class="dia_content">
          <div class="left">
            <div class="top_inp">
              <el-input
                v-model="inpValue"
                placeholder="请输入用户名"
                prefix-icon="el-icon-search"
                @keydown.enter.native="inpSelect"
              ></el-input>
            </div>
            <div class="left_contacts">
              <ul style="padding: 0%">
                <li class="contact-item" v-for="res in userlist" :key="res.id">
                  <!-- 单选框 -->
                  <el-checkbox
                    v-model="selectedContacts"
                    :label="res.id"
                    @change="handleChange(res)"
                    class="checkbox-no-label"
                  ></el-checkbox>
                  <el-avatar
                    :src="res.avatar"
                    shape="square"
                    style="margin-right: 10px"
                  ></el-avatar>
                  <span>{{ res.username }}</span>
                </li>
              </ul>
            </div>
          </div>
          <div class="right">
            <div class="r_show" v-for="item in selectUser" :key="item.id">
              <el-avatar
                :src="item.avatar"
                shape="square"
                style="margin-right: 10px"
              ></el-avatar>
              <div>{{ item.username }}</div>
            </div>
            <div class="button">
            <el-button type="primary" @click="dialogVisible = false"
              >发起群聊</el-button
            >

            <el-button type="info" @click="dialogVisible = false"
              >取消</el-button
            >
          </div>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
  
  <script>
import { onMounted } from "vue";
import CHAT from "../../views/chatViews/index.vue";
export default {
  name: "userlist",
  components: {
    CHAT,
  },
  data() {
    return {
      restaurants: [],
      state: "",
      timeout: null,
      imageSrc: "",
      userlist: [],
      contactList: [],
      selectValue: "",
      UnreadTotal: 0,
      responseFirst: [],
      indexId: 0,
      dialogVisible: false,
      inpValue: "",
      selectedContacts: [], // 存储选中联系人id
      selectUser: [], // 存储选中联系人的详细信息
    };
  },
  methods: {
    //将用户信息传递给聊天页面
    getSingleUser(res) {
      this.$emit("getSingleUser", res);
      if (this.$route.path != "/" && this.$route.path != "/index") {
        this.$router.push({ path: "/index", query: { id: res.id } });
      }
      this.indexId = res.id;


      //将res存入state中
      this.$store.commit("setSingleUser", res);      
      
      //将消息设置为已读
      this.setRead(res.id);
    },

    //将消息设置为已读
    setRead(id) {
      let url = "/api/im/read/" + id;
      this.$http.get(url).then((res) => {
        if (res.data.data != null) {
          this.getFriendInfo();
        }
      });
    },

    //回车监听获取用户信息
    handleEnter() {
      let url = "/api/im/user/get?" + "username=" + this.selectValue;
      this.$http.get(url).then((res) => {
        if (res.data.data != null) {
        }
      });
    },
    loadAllUser() {
      this.$http.get("/api/im/user/get").then((res) => {
        if (res.data.data != null) {
          // 创建包含用户名和ID的数组
          const suggestionsWithValue = res.data.data.map((item) => ({
            value: item.username,
            id: item.id,
          }));
          // 将新数组赋值给 contactList
          this.contactList = suggestionsWithValue;
          this.restaurants = this.contactList; // 同步到 restaurants
        }
      });
    },

    querySearchAsync(queryString, cb) {
      var results = queryString
        ? this.restaurants.filter(this.createStateFilter(queryString))
        : this.restaurants;

      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      });
    },

    createStateFilter(queryString) {
      return (state) => {
        return (
          state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
    handleSelect(item) {
      this.selectValue = item.value;
    },
    addContacts() {
      this.dialogVisible = true;
    },

    //获取最近的一条聊天记录
    getRecentChatRecord(id) {
      let url = "/api/im/message/latest/" + id;
      this.$http.get(url).then((res) => {
        if (res.data.data != null) {
          this.userlist.forEach((item, index) => {
            if (item.id == id) {
              this.$set(item, "content", res.data.data.content);
              this.$set(item, "time", res.data.data.createTime);
            }
          });
        }
      });
    },

    //获取好友的信息
    getFriendInfo() {
      this.$http.get("/api/im/user/list").then((res) => {
        if (res.data.data != null) {
          this.userlist = res.data.data;
          //默认显示第一个用户的信息
          // this.$emit("getSingleUser", this.userlist[0]);
          this.userlist = res.data.data.map((user) => {
            return {
              ...user,
              count: 0, // 添加 count 属性
              content: "", // 添加 content 属性
              time: "", // 添加 time 属性
            };
          });
          //获取未读聊天记录
          this.userlist.forEach((item) => {
            this.getChatRecord(item.id);
            this.getRecentChatRecord(item.id);
          });
        }
      });
    },
    // 获取未读聊天记录
    getChatRecord(id) {
      let url = "/api/im/message/unread/" + id;

      this.$http.get(url).then((res) => {
        if (res.data.data != null) {
          let data = res.data.data;
          this.UnreadTotal += data;
          // console.log(this.UnreadTotal);
          this.$store.commit("setUnreadTotal", this.UnreadTotal);
          // 遍历 userlist 数组，找到 id 相同的元素
          this.userlist.forEach((item, index) => {
            if (item.id == id) {
              // 确保 count 属性是响应式的
              this.$set(item, "count", data);
            }
          });
        }
      });
      this.$store.commit("setUnreadTotal", this.UnreadTotal);
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    handleMouseDown(event) {
      const dialog = this.$refs.dialog.$el; // 获取 dialog DOM 元素
      let offsetX = event.clientX - dialog.getBoundingClientRect().left;
      let offsetY = event.clientY - dialog.getBoundingClientRect().top;

      const handleMouseMove = (e) => {
        dialog.style.left = `${e.clientX - offsetX}px`;
        dialog.style.top = `${e.clientY - offsetY}px`;
      };

      const handleMouseUp = () => {
        document.removeEventListener("mousemove", handleMouseMove);
        document.removeEventListener("mouseup", handleMouseUp);
      };

      document.addEventListener("mousemove", handleMouseMove);
      document.addEventListener("mouseup", handleMouseUp);
    },
    handleChange(contact) {
      // 判断选中状态
      const isSelected = this.selectedContacts.includes(contact.id);
      if (isSelected) {
        this.selectUser.push(contact);
        console.log(`选中联系人:`, this.selectUser);
      } else {
        // 移除选中联系人
        this.selectUser = this.selectUser.filter(
          (item) => item.id !== contact.id
        );

        console.log(`未选中联系人:`, this.selectUser);
      }
    },
  },
  mounted() {
    this.loadAllUser();
    this.getFriendInfo();
  },
};
</script>
  
  <style lang="less" scoped>
#userlist {
  width: 260px;
  height: 700px;
  background-color: #ffffff;
  border-left: 1px solid #ccc;
  .top {
    display: flex;
    width: 260px;
    height: 40px;
    border-bottom: 1px solid #ccc;
    /deep/ .el-input__inner {
      border: none;
      background-color: #f5f5f5;
    }
    .add {
      width: 40px;
      height: 40px;
      background-color: #f5f5f5;
      text-align: center;
      &:hover {
        background-color: #e6e6e6;
      }
      i {
        font-size: 20px;
        color: #ccc;
        line-height: 40px;
        text-align: center;
      }
    }
  }

  .list {
    width: 260px;
    height: 660px;

    overflow-y: auto; /* 当内容超过高度时显示滚动条 */

    .content {
      width: 260px;
      height: 60px;
      margin-top: 5px;
      display: flex;
      cursor: default;
      .img {
        position: relative;
        width: 60px;
        height: 60px;
        padding-left: 5px;
        margin-top: 5px;
        .count {
          position: absolute;
          width: 20px;
          height: 20px;
          background-color: #ec4c4c;
          color: #ffffff;
          border-radius: 50%;
          text-align: center;
          line-height: 20px;
          left: 42px;
          top: -9px;
        }
      }
      .center {
        width: 120px;
        height: 60px;
        margin-left: 5px;
        margin-top: 5px;
        .username {
          width: 100px;
          height: 20px;
          span {
            font-size: 14px;
            color: #4b4b4b;
          }
        }
        .message {
          width: 100px;
          height: 30px;
          //超过隐藏多余部分
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          color: #c6ced0;
          span {
            font-size: 11px;
            color: #c6ced0;
          }
        }
      }
      .time {
        width: 80px;
        height: 60px;
        padding-right: 5px;
        line-height: 65px;
        margin-top: 5px;
        //超过隐藏多余部分
        overflow: hidden;
        text-overflow: ellipsis;

        span {
          font-size: 12px;
          color: #c6ced0;
        }
      }
    }
    .content:hover {
      background-color: #e6e6e6;
    }
    .clickBag {
      background-color: #e6e6e6;
    }
  }
}

#dialog {
  .dia_content {
    display: flex;
    .left {
      width: 50%;
      height: 400px;
      border-right: 1px solid #e9e9e9;
      .top_inp {
        width: 94%;
        height: 40px;
        padding: 10px 10px;
        padding-bottom: 0%;
        /deep/ .el-input--prefix .el-input__inner {
          height: 30px !important;
          border-radius: 35px !important;
        }
        /deep/ .el-input__prefix {
          top: -5px;
        }
      }

      .left_contacts {
        height: 320px;
        overflow-y: auto;
        padding: 10px 10px;
        padding-top: 0%;

        .contact-item {
          display: flex;
          align-items: center;
          height: 50px;
          padding: 10px 10px;
          cursor: pointer;
          border-radius: 5px;
          &:hover {
            background-color: #f5f5f5;
          }
          .el-checkbox {
            margin-right: 10px;
          }
          /deep/ .el-checkbox__label {
            display: none; /* 隐藏 label */
          }
          .el-avatar {
            margin-right: 10px;
          }
          span {
            font-size: 14px;
          }
        }
      }
    }
    .right {
      width: 50%;
      height: 400px;
      position: relative;
      .r_show {
        float: left;
        width: 50px;
        height: 90px;
        padding: 10px 10px;

        .el-avatar {
          margin-right: 10px;
        }
        div {
          // 多余文字隐藏
          width: 50px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          font-size: 14px;
        }
      }
      .button {
        position: absolute;
        bottom: 10px;
        left: 60%;
        transform: translateX(-50%);
        width: 100px;
        display: flex;
        justify-content: space-between;
      }
    }
  }
}

/deep/ .el-dialog__body {
  padding: 0px 0px;
}
/deep/ .el-dialog__header {
  padding: 0px 0px 0px;
}
</style>    
  